import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:maihealth/class/home/model/homeModel.dart';
import 'package:maihealth/class/home/model/ziXunModel.dart';
import 'package:maihealth/class/home/provide/homeProvide.dart';
import 'package:maihealth/class/main/commonHeader.dart';
import 'package:maihealth/class/main/webPage.dart';
import 'package:maihealth/utils/constant.dart';
import 'package:maihealth/utils/httpUtils.dart';
import 'package:maihealth/utils/router.dart';
import 'package:maihealth/utils/screenUtil.dart';
import 'package:maihealth/utils/toast.dart';
import 'package:provide/provide.dart';
import 'package:maihealth/class/main/loadError.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:maihealth/utils/refreshConfig.dart';
import 'package:maihealth/class/main/scrollIndicator.dart';
class homePage extends StatefulWidget {
  homePage({Key key}) : super(key: key);
  _homePageState createState() => _homePageState();
}

class _homePageState extends State<homePage> with AutomaticKeepAliveClientMixin{
  homeProvide provide;
  homeModel model;
  int _page = 1;
  bool _loadMore = false;//是否加载更多
  final List<Map<String,String>> itemsIcons = [
    {'icon':'images/home/home_zlxm.png','title':'好脉服务','desc':'内容介绍、项目详情'},
    {'icon':'images/home/home_zlxm.png','title':'健康管家','desc':'您的专属管家'},
    {'icon':'images/home/home_shop.png','title':'健康商城','desc':'健康周边商品服务'},
    {'icon':'images/home/home_vip.png','title':'好脉会员','desc':'好脉会员专属特权'},
  ];
@override
  @override
  Widget build(BuildContext context) {
    provide = Provide.value<homeProvide>(context);
    return  Scaffold(
        body: FutureBuilder(
          future: model != null ? null : _requestHomeData(),
          builder: (context,snapshot){
            print('snapshot.connectionState===${snapshot.connectionState}');
            print('snapshot.hasData===${snapshot.hasData}');
            print('snapshot.hasError===${snapshot.hasError}');
            if (snapshot.hasData) {//成功
              return _setUpListView();
            } if (snapshot.hasError) {//失败         
              return  Center(
                child: loadError(
                  errorText: snapshot.error,
                  reload: (){
                    setState(() {});//一个小技巧,在网络异常的时候让他重绘制
                }),
              );
            }else{//开始请求
              return Center(
                child: CircularProgressIndicator(),
              );
            }
          }
        ),
      );
  }
  //初始化listView
  Widget _setUpListView(){
    return MediaQuery.removePadding(
      removeTop: true,
      context: context,
      child: Container(
        child: scrollIndicator(
          child: EasyRefresh(
            key: easyRefreshKey,
            autoLoad:true,
            child:  ListView.builder(
            itemCount: provide.listDatas.length+6,
            itemBuilder: (BuildContext context, int index) {
            if (index==0) {//首页轮播
              return _setUpSWiper();
            }else if(index==1){//4大类别
              return _setUpHeaderItems();
            }else if(index==2){//4大类别
              return _setUpServers();
            }else if(index==3){//健康应用
              return _healthApplication();
            }else if(index==4){//健康设备
              return _healthDevices();
            }else if(index==5){//健康圈头部
              return commonHeader(title:'健康圈');
            }else{//资讯列表
              return _ziXunListItem(index-6);
            }
          }), 
            refreshHeader: refresh_Header,
            refreshFooter: refresh_Footer,
            onRefresh:  () async{//下拉刷新
              _page = 1;
              await _requestZiXunData();
            },
            loadMore: _loadMore ? () async {//上拉加载更多
              await _requestZiXunData();
            } : null
          ),
        ),
      )
     );
  }
  //初始化轮播
  Widget _setUpSWiper(){
      return Container(
        height: setHeight(200),
        width: kscreenW,
        child: new Swiper(
          itemBuilder: (BuildContext context,int index){
           Thumbnails thumbnail =  this.model.thumbnails[index];
           String url = HttpUtils.API_PREFIX + thumbnail.url;
            return new Image.network(url,fit: BoxFit.fill,);
          },
          itemCount: this.model.thumbnails.length,
          pagination: this.model.thumbnails.length >1 ? new SwiperPagination() : null,
          onTap: (index){
            print('点击index===${index}');
          },
          autoplay: false
        )
      );
  }
  
  //初始化4大类别
  Widget _setUpHeaderItems(){
    return Container(
      margin: EdgeInsets.only(left: setWidth(15),right: setWidth(15),top: setHeight(20)),
      height: setHeight(101),
      child: Wrap(
        spacing: setWidth(5),
        runSpacing: setWidth(5),
        direction: Axis.horizontal,
        children: <Widget>[
          _headerItem(0),
          _headerItem(1),
          _headerItem(2),
          _headerItem(3),
        ],
      )
    );
  }
  //初始化4大类Item
  Widget _headerItem(int index){
  Map item = itemsIcons[index];
  return Container(
    width: setWidth(170),
    height: setHeight(48),
    color: Color(0xFFF2F2F2),
    padding: EdgeInsets.only(left: 10,right: 10),
    child: Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        Expanded(
          child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
              Text(item['title'],style:TextStyle(color: ThemeBlackColor,fontSize: setFont(15),fontWeight: FontWeight.bold)),
              Text(item['desc'],overflow: TextOverflow.ellipsis,style:TextStyle(color: ThemeGrayTextColor,fontSize: setFont(12))),
          ],
         )
        ),
        Image.asset(item['icon'],fit: BoxFit.fill,width: setWidth(30),height: setWidth(30))
      ],
    ),
  );
}

  //初始化核心服务
  Widget _setUpServers(){
return Column(
  children: <Widget>[
    commonHeader(title:'特色服务'),//头部标题
    _serverScrollView()
  ],
);
}
  //核心服务列表
  Widget _serverScrollView(){
  return Container(
    height: setHeight(70),
    width: kscreenW,
    padding: EdgeInsets.only(left: setWidth(15)),
    child: ListView.builder(
        scrollDirection: Axis.horizontal,
        itemCount: model.services.length ,
        itemBuilder: (BuildContext context, int index) {
        Services server = this.model.services[index];
        String url = HttpUtils.API_PREFIX+server.thumbnail;
        return Container(
          padding: EdgeInsets.only(right: setWidth(10)),
          child: Stack(
            alignment: Alignment.center,
            children: <Widget>[
                ClipRRect(
                  borderRadius: BorderRadius.circular(5),
                  child: Image.network(
                    url,
                    width: setWidth(135),
                    fit: BoxFit.fill,
                  )
                ),
                InkWell(
                  onTap: (){
                    print('点击');
                  },
                  child:Container(
                  alignment: Alignment.center,
                  width: setWidth(135),
                  height: setHeight(70),
                  child: Text(server.title,style: TextStyle(fontSize: 18,fontWeight: FontWeight.bold,color: Colors.white),),
                   decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(5),
                      color: Color.fromRGBO(0, 0, 0, 0.5),
                  ),
                ),
               )  
             ],
          )
        );
      },
    )
  );
}
  //健康应用
  Widget _healthApplication(){

  return Column(
    children: <Widget>[
      commonHeader(title:'健康应用'),
      __healthApplicationItem(0)
    ],
  );  
 }
  Widget __healthApplicationItem(int index){
    Diagnosis diagnosis =  model.diagnosis[index];
    String url = HttpUtils.API_PREFIX + diagnosis.thumbnail;
    return Container(
      width: kscreenW,
      padding: EdgeInsets.only(left: setWidth(15),right: setWidth(15),bottom: setHeight(10)),
      child: Stack(
        children: <Widget>[
          ClipRRect(
            borderRadius: BorderRadius.circular(4),
            child: Image.network(url,width: setWidth(345),height: setHeight(120),fit: BoxFit.cover)
          ),
          Container(
            padding: EdgeInsets.only(left: 10,right: 10),
            width: setWidth(345),
            height: setHeight(120),
            decoration: BoxDecoration(
              color: Color.fromRGBO(0, 0, 0, 0.5),
              borderRadius:  BorderRadius.circular(4),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text(diagnosis.title,style: TextStyle(fontSize: setFont(20),fontWeight: FontWeight.bold,color: Colors.white),),
                SizedBox(height: 10),
                Text(diagnosis.desc,style: TextStyle(fontSize: setFont(14),color: Colors.white),)
              ],
            ),
          )
        ],
      )
    );
  }
 //健康设备
 Widget _healthDevices(){
  return Column(
    children: <Widget>[
      commonHeader(title: '健康设备'),
      Column(
        children: _allDevices()
      )
    ],
  );
 }

 List<Widget>_allDevices(){
      List<Widget> lists = [];
     for (var device in model.devices) {
         Widget item =  _deviceItem(device);
        lists.add(item);
     }
    return lists;
 }
 //健康设备
 Widget _deviceItem(Devices device){
   String url = device.logo;
   print('url===${url}');
   return Container(
    padding: EdgeInsets.only(left: setWidth(15),right: setWidth(15)),      
     width: kscreenH,
     height: setHeight(60),
     child: Row(
       children: <Widget>[
         Image.network(url,width: setWidth(60),height: setWidth(60),fit: BoxFit.cover),
         Expanded(
           child: Column(
             crossAxisAlignment: CrossAxisAlignment.start,
             mainAxisAlignment: MainAxisAlignment.center,
             children: <Widget>[
               Text(device.name,style: TextStyle(fontSize: setFont(17)),overflow: TextOverflow.ellipsis,),
               Text(device.desc,style: TextStyle(fontSize: setFont(11),color: ThemeGrayTextColor),overflow: TextOverflow.ellipsis,),
             ],
           )
         ),
          Container(
            margin: EdgeInsets.only(left: 10),
            height: setHeight(24),
            width: setWidth(75),
            alignment: Alignment.center,
            child:ClipRRect(
              borderRadius: BorderRadius.circular(12),
              child:RaisedButton(
                child: Text('去绑定',style: TextStyle(fontSize: 12,color: Colors.white),),
                color: ThemeColor,
                onPressed: (){
                  print('点击去绑定...');
                },
             )
            )
           )
       ],
     ),
   );
 }

//获取首页数据
Future  _requestHomeData()async{
  homeModel model = await provide.requestHomeData();
  this.model = model;
   _requestZiXunData();//获取资讯列表
  return model;
}

//请求资讯数据
 Future _requestZiXunData() async{
   try {
    int  count = await  provide.requestZiXunListData(_page);
    _page++;
    setState(() {
      _loadMore = count>=ROW;
    });
    return count;
   } catch (e) {
     showToast(e);
   }
 }
 //资讯列表
 Widget _ziXunListItem(int index){
    ziXunModel model = provide.listDatas[index];
    String url = HttpUtils.API_PREFIX + model.thumbnail;
    return InkWell(
      onTap: (){
          String url = HttpUtils.API_PREFIX +model.url;
          Router.push(context, webPage(url: url));
      },
      child: Container(
        height: setHeight(90),
        padding: EdgeInsets.only(left: setWidth(15),right: setWidth(15),top: setHeight(10),bottom: setHeight(10)),
        child: Row(
          children: <Widget>[
            Container(
              child:   Image.network(url,width: setWidth(120),height: setHeight(70),fit: BoxFit.cover),
              margin: EdgeInsets.only(right: setWidth(15)),
            ),
        
            Expanded(
              child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                //标题
                Text(model.title,style:TextStyle(fontSize: 14),overflow: TextOverflow.ellipsis,maxLines: 2),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    //标签
                    Container(
                      height: 16,
                      padding: EdgeInsets.only(left: 5,right: 5),
                      decoration: BoxDecoration(
                          border: Border.all(color: ThemeColor,width: 1),
                          borderRadius: BorderRadius.circular(8)
                      ),
                      child:Text(model.tag,style:TextStyle(fontSize:10,color: ThemeColor))
                    ),
                    Text(model.date,style:TextStyle(fontSize:12,color: ThemeGrayTextColor)),
                  ],
                )
              ],
              )  
            )
          ]
        )
      )
    ); 
 }
 @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    print('首页销毁');
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
